<template>
  <div>
    <div  class="span1">
      <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 10px;">
        <label style="color: #808080; margin: 0; white-space: nowrap;">当前权重展示</label>
        <div style="display: flex; align-items: center; color: #808080">
          选择专业：
          <DropdownList
            title="综合"
            :menuItems="menudata"
            @item-click="handleMenuClick"
          />
        </div>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      height="250"
      border
      style="width: 100%;height: 100%">

      <el-table-column label="生源状态" header-align="center" align="center">
        <el-table-column label="生源水平" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_lqfs"
                           label="录取分数"
                           width="90">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_dyzyl"
                           label="第一志愿率"
          >
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_bdl"
                           width="90"
                           label="报到率">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_jhzss"
                           label="计划招生数"
                           width="90">

          </el-table-column>
        </el-table-column>

        <el-table-column label="专业认可度" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_ysylzy" width="90"
                           label="优势（一流）专业">


          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_zzyqk"  width="90"
                           label="转专业情况">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_zymyd" width="90" label="专业认可度">

          </el-table-column>
        </el-table-column>
      </el-table-column>

      <el-table-column label="培养过程" header-align="center" align="center">
        <el-table-column label="高层次人才" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_gccch" width="90"
                           label="高层次称号">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_gcctd" width="90"
                           label="高层次团队">

          </el-table-column>
        </el-table-column>

        <el-table-column label="师资队伍" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_sljg" width="90"
                           label="数量结构">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_jxsp" width="90"
                           label="教学水平">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_kysp" width="90"
                           label="科研水平">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_ssb" width="90"
                           label="师生比">

          </el-table-column>
        </el-table-column>

        <el-table-column label="资源配置" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_syjx" width="90"
                           label="专业实验教学校内场所情况">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_sxsjsxjdqk" width="90"
                           label="实习实践实训基地情况">
          </el-table-column>
        </el-table-column>
        <el-table-column label="课程质量" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_ylkcjs" width="90"
                           label="一流课程建设">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_cbjczl" width="90"
                           label="出版教材质量">

          </el-table-column>

          <el-table-column header-align="center" align="center"
                           prop="qz_xxhkcjs" width="90"
                           label="信息化课程建设">

          </el-table-column>
        </el-table-column>
      </el-table-column>

      <el-table-column label="学生发展与就业" header-align="center" align="center">
        <el-table-column label="学生成长" header-align="center" align="center">

          <el-table-column header-align="center" align="center"
                           prop="qz_gyxljyhdcyqk" width="90"
                           label="高影响力教育活动参与情况">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_xxcx" width="90"
                           label="学习成效">

          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_lwcjhgl" width="90"
                           label="论文抽检合格率">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_byzhxlqk" width="90"
                           label="毕业综合训练情况">
          </el-table-column>
        </el-table-column>

        <el-table-column label="就业质量" header-align="center" align="center">
          <el-table-column header-align="center" align="center"
                           prop="qz_jyl" width="90"
                           label="就业率">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_kyl" width="90"
                           label="考研率">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_jyqx" width="90"
                           label="就业去向">
          </el-table-column>
          <el-table-column header-align="center" align="center"
                           prop="qz_jyyzyxgd" width="90"
                           label="就业与专业相关度">
          </el-table-column>
        </el-table-column>`
      </el-table-column>
    </el-table>
  </div>
  <div class="button">
    <el-button type="primary" @click="quanzhong">修改权重</el-button>
  </div>
  <form-drower  ref="formDrawerRef" title="修改权重" destroyOnClose @submit="onSubmit" :admissionScores="admissionScores" size="85%" >
    <template #header>
      <div style="display: flex; align-items: center; margin: 0px 0px 10px 0px;color: #808080">
        修改专业：
        <DropdownList
          :title="title"
          :menuItems="menudata"
          @item-click="handleMenuClick2"
        />
      </div>
    </template>
    <el-table :data="QzData" border style="width: 100%"  :span-method="getSpanMethod">
      <!-- 一级指标列 -->
      <el-table-column prop="level1" label="一级指标" width="150" align="center" />

      <!-- 一级指标权重列 -->
      <el-table-column label="权重值" width="225" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.sourceStatus"
            :precision="10"
            :step="0.1"
            @change="(val) => {updateWeight(val, row, 'sourceStatus')}"
            :min="0"
            style="width: 100%"
          />
        </template>
      </el-table-column>

      <!-- 二级指标列 -->
      <el-table-column prop="level2" label="二级指标" width="180" align="center" />

      <!-- 二级指标权重列 -->
      <el-table-column label="权重值" width="225" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.sourceLevel"
            :precision="10"
            :step="0.1"
            @change="(val) => {updateWeight(val, row, 'sourceLevel')}"
            :min="0"
            style="width: 100%"
          />
        </template>
      </el-table-column>

      <!-- 三级指标列 -->
      <el-table-column prop="level3" label="三级指标" width="190" align="center" />

      <!-- 三级指标权重列 -->
      <el-table-column label="权重值" width="225" align="center">
        <template #default="{ row }">
          <el-input-number
            v-model="row.admissionScore"
            :precision="10"
            :step="0.1"
            :min="0"
            @change="(val) => updateWeight(val, row, 'admissionScore')"
            style="width: 100%"
          />
        </template>
      </el-table-column>
    </el-table>
  </form-drower>
</template>

<script setup>
import {ref} from "vue";
import FormDrower from "@/components/FormDrower.vue";
import axios from "axios";
import { ElMessage } from 'element-plus';
import { useQzStore } from "@/stores/quanzhong.js";
import DropdownList from "@/components/DropdownList.vue"

//展示权重表格数据
const tableData = ref([
  {
    qz_lqfs: '',
    qz_dyzyl: '',
    qz_bdl: '',
    qz_jhzss:'',
    qz_ysylzy: '',
    qz_zzyqk: '',
    qz_zymyd: '',
    qz_gccch: '',
    qz_gcctd: '',
    qz_sljg: '',
    qz_jxsp: '',
    qz_kysp: '',
    qz_ssb: '',
    qz_yszy: '',
    qz_syjx: '',
    qz_sxsjsxjdqk: '',
    qz_ylkcjs: '',
    qz_cbjczl: '',
    qz_xxhkcjs: '',
    qz_gyxljyhdcyqk: '',
    qz_xxcx: '',
    qz_lwcjhgl: '',
    qz_byzhxlqk: '',
    qz_jyl: '',
    qz_kyl: '',
    qz_jyqx: '',
    qz_jyyzyxgd: '',
  }
])

//设置权重表格数据
const QzData = ref([

  { level1: '生源状态', sourceStatus: 0,level2: '生源水平', sourceLevel: 0,level3: '录取分数', admissionScore:0 },
  { level1: '生源状态', sourceStatus: 0, level2: '生源水平', sourceLevel: 0,level3: '第一志愿率', admissionScore: 0},
  { level1: '生源状态', sourceStatus: 0, level2: '生源水平', sourceLevel: 0,level3: '报到率', admissionScore: 0},
  {level1: '生源状态', sourceStatus: 0, level2: '生源水平', sourceLevel: 0, level3: '招生计划数', admissionScore: 0},
  { level1: '生源状态', sourceStatus: 0, level2: '专业认可度', sourceLevel: 0,level3: '优势(一流)专业', admissionScore: 0},
  { level1: '生源状态', sourceStatus: 0, level2: '专业认可度', sourceLevel: 0,level3: '转专业情况', admissionScore: 0},
  { level1: '生源状态', sourceStatus: 0, level2: '专业认可度', sourceLevel: 0,level3: '专业满意度', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '高层次人才', sourceLevel: 0, level3: '高层次称号', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '高层次人才', sourceLevel: 0, level3: '高层次团队', admissionScore: 0 },


  // 师资队伍
  { level1: '培养过程', sourceStatus: 0, level2: '师资队伍', sourceLevel: 0, level3: '数量结构', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '师资队伍', sourceLevel: 0, level3: '教学水平', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '师资队伍', sourceLevel: 0, level3: '科研水平', admissionScore: 0 },
  {level1: '培养过程', sourceStatus: 0, level2: '师资队伍', sourceLevel: 0, level3: '师生比', admissionScore: 0},

  // 资源配置
  { level1: '培养过程', sourceStatus: 0, level2: '资源配置', sourceLevel: 0, level3: '专业实验教学校内场所情况', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '资源配置', sourceLevel: 0, level3: '实习实践实训基地情况', admissionScore: 0 },

  // 课程质量
  { level1: '培养过程', sourceStatus: 0, level2: '课程质量', sourceLevel: 0, level3: '一流课程建设', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '课程质量', sourceLevel: 0, level3: '出版教材质量', admissionScore: 0 },
  { level1: '培养过程', sourceStatus: 0, level2: '课程质量', sourceLevel: 0, level3: '信息化课程建设', admissionScore: 0 },


  // 学生成长
  { level1: '学生发展与就业', sourceStatus: 0, level2: '学生成长', sourceLevel: 0, level3: '高影响力教育活动参与情况', admissionScore: 0 },
  { level1: '学生发展与就业', sourceStatus: 8, level2: '学生成长', sourceLevel: 4, level3: '学习成效', admissionScore: 1 },
  { level1: '学生发展与就业', sourceStatus: 8, level2: '学生成长', sourceLevel: 4, level3: '论文抽检合格率', admissionScore: 1 },
  { level1: '学生发展与就业', sourceStatus: 8, level2: '学生成长', sourceLevel: 4, level3: '毕业综合训练情况', admissionScore: 1 },

  // 就业质量
  { level1: '学生发展与就业', sourceStatus: 8, level2: '就业质量', sourceLevel: 4, level3: '就业率', admissionScore: 1},
  { level1: '学生发展与就业', sourceStatus: 8, level2: '就业质量', sourceLevel: 4, level3: '考研率', admissionScore: 1},
  { level1: '学生发展与就业', sourceStatus: 8, level2: '就业质量', sourceLevel: 4, level3: '就业去向', admissionScore: 1 },
  { level1: '学生发展与就业', sourceStatus: 8, level2: '就业质量', sourceLevel: 4, level3: '就业与专业相关度', admissionScore: 1 },



])

//映射表
const menudata = ref([
  {label:'农学', value:'农学'},
  {label:'医学', value:'医学'},
  {label:'历史学', value:'历史学'},
  {label:'哲学', value:'哲学'},
  {label:'工学', value:'工学'},
  {label:'建筑学', value:'建筑学'},
  {label: '教育学', value:'教育学'},
  {label: '文学', value:'文学'},
  {label: '法学', value: '法学'},
  {label: '理学', value: '理学'},
  {label:'管理学', value: '经济学'},
  {label: '艺术学', value: '艺术学'},
  {label:'综合', value: '综合'}
])
const level3ToFieldMap = {
  '录取分数': 'qz_lqfs',
  '第一志愿率': 'qz_dyzyl',
  '报到率': 'qz_bdl',
  '招生计划数': 'qz_jhzss',
  '优势(一流)专业': 'qz_ysylzy',
  '转专业情况': 'qz_zzyqk',
  '专业满意度': 'qz_zymyd',
  '高层次称号': 'qz_gccch',
  '高层次团队': 'qz_gcctd',
  '数量结构': 'qz_sljg',
  '教学水平': 'qz_jxsp',
  '科研水平': 'qz_kysp',
  '师生比': 'qz_ssb',
  '专业实验教学校内场所情况': 'qz_syjx',
  '实习实践实训基地情况': 'qz_sxsjsxjdqk',
  '一流课程建设': 'qz_ylkcjs',
  '出版教材质量': 'qz_cbjczl',
  '信息化课程建设': 'qz_xxhkcjs',
  '高影响力教育活动参与情况': 'qz_gyxljyhdcyqk',
  '学习成效': 'qz_xxcx',
  '论文抽检合格率': 'qz_lwcjhgl',
  '毕业综合训练情况': 'qz_byzhxlqk',
  '就业率': 'qz_jyl',
  '考研率': 'qz_kyl',
  '就业去向': 'qz_jyqx',
  '就业与专业相关度': 'qz_jyyzyxgd'
};

const selectlabel = ref('综合');
let title = ref('综合');


const handleMenuClick = (item) => {
  selectlabel.value = item.label;
  console.log('选择的label:', item.label);
  title.value = item.label;
  try {
    fetchWeightsAndUpdate({
      selectlabel,
      QzData,
      calculateAllWeights,
      updateTableData
    });

    console.log('权重更新成功');
  } catch (error) {
    console.error('处理权重时出错:', error);
    // 可以在这里添加用户提示等错误处理
  }

}

const selectlabel2 = ref('综合');
const handleMenuClick2 = (item) =>{
  selectlabel2.value = item.label;
  try {
    fetchWeightsAndUpdate({
      selectlabel,
      QzData,
      calculateAllWeights,
    });
    console.log('权重更新成功');
  } catch (error) {
    console.error('处理权重时出错:', error);
    // 可以在这里添加用户提示等错误处理
  }
}
// 根据三级权重数据更新所有数据，计算权重
const calculateAllWeights = (data) => {
  // 1. 计算二级指标权重(sourceLevel)
  const level2Sums = data.reduce((acc, item) => {
    const key = `${item.level1}-${item.level2}`;
    acc[key] = (acc[key] || 0) + item.admissionScore;
    return acc;
  }, {});

  // 1.5 先更新sourceLevel
  data = data.map(item => ({
    ...item,
    sourceLevel: level2Sums[`${item.level1}-${item.level2}`] || 0
  }));

  // 2. 计算一级指标权重(sourceStatus)
  const level1Sums = data.reduce((acc, item) => {
    // 对每个一级指标下的所有二级指标sourceLevel求和
    if (!acc[item.level1]) {
      acc[item.level1] = 0;
    }
    // 确保每个二级指标只加一次（去重）
    if (item.level3) { // 如果是三级指标行
      const key = `${item.level1}-${item.level2}`;
      if (!acc.seenKeys) acc.seenKeys = new Set();
      if (!acc.seenKeys.has(key)) {
        acc[item.level1] += item.sourceLevel;
        acc.seenKeys.add(key);
      }
    }
    return acc;
  }, {});

  // 3. 更新sourceStatus
  data = data.map(item => ({
    ...item,
    sourceStatus: level1Sums[item.level1] || 0
  }));

  return data;
};

//  更新tableData的值
const updateTableData = () => {
  // 创建一个新对象来存储更新后的值
  const updatedTableData = {...tableData.value[0]};

  QzData.value.forEach(item => {
    const fieldName = level3ToFieldMap[item.level3];
    if (fieldName && updatedTableData.hasOwnProperty(fieldName)) {
      updatedTableData[fieldName] = item.admissionScore.toString();
    }
  });

  tableData.value = [updatedTableData];
};


/**
 * 获取权重数据并更新相关状态
 * @param {Ref} selectlabel - 选择的标签值引用
 * @param {Ref} QzData - 需要更新的响应式数据引用
 * @param {Function} calculateAllWeights - 计算权重函数
 * @param {Function} updateTableData - 更新表格数据函数
 * @returns {Promise<void>}
 */
async function fetchWeightsAndUpdate({
                                       selectlabel,
                                       QzData,
                                       calculateAllWeights,
                                       updateTableData
                                     }) {
  try {
    // 1. 发起API请求获取权重数据
    const response = await axios({
      url: 'http://localhost:8081/getweight',
      method: 'get',
      headers: {
        Authorization: 'Bearer ' + localStorage.getItem('jwt_token'),
      },
      params: {
        syxwml: selectlabel.value
      }
    });

    if (!response.data?.weight) {
      throw new Error('无效的响应数据: 缺少weight字段');
    }

    const zbqzArray = response.data.weight;
    console.log('获取到的权重数据:', zbqzArray);

    // 2. 创建指标名称到权重的映射表
    const zbqzMap = zbqzArray.reduce((map, item) => {
      if (item.zbmc && item.zbqz !== undefined) {
        map[item.zbmc] = item.zbqz;
      } else {
        console.warn('无效的权重数据项:', item);
      }
      return map;
    }, {});

    // 3. 更新QzData中的admissionScore
    let unmatchedCount = 0;
    QzData.value = QzData.value.map(item => {
      const matchedZbqz = zbqzMap[item.level3];

      if (matchedZbqz === undefined) {
        unmatchedCount++;
        return item;
      }

      return {
        ...item,
        admissionScore: matchedZbqz
      };
    });

    // 4. 记录未匹配的项
    if (unmatchedCount > 0) {
      const unmatchedItems = QzData.value.filter(item => zbqzMap[item.level3] === undefined);
      console.warn(`${unmatchedCount}个level3值未找到匹配的zbmc:`,
        unmatchedItems.map(item => item.level3).join(', '));
    }

    // 5. 计算并更新权重
      QzData.value = calculateAllWeights(QzData.value);
    if(updateTableData !== undefined){
        updateTableData()
    }
    console.log('更新后的QzData:', QzData.value);
    return QzData.value;

  } catch (error) {
    console.error('获取或处理权重数据失败:', error);
    throw error; // 重新抛出错误以便调用方处理
  }
}
// 合并单元格方法

fetchWeightsAndUpdate({
    selectlabel,
    QzData,
    calculateAllWeights,
    updateTableData
});
const getSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 处理一级指标和对应权重列(第0列和第1列)
  if (columnIndex === 0 || columnIndex === 1) {
    const prevRow = QzData.value[rowIndex - 1]
    if (!prevRow || prevRow.level1 !== row.level1) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < QzData.value.length; i++) {
        if (QzData.value[i].level1 === row.level1) {
          rowspan++
        } else {
          break
        }
      }
      return { rowspan, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 处理二级指标和对应权重列(第2列和第3列)
  if (columnIndex === 2 || columnIndex === 3) {
    const prevRow = QzData.value[rowIndex - 1]
    if (!prevRow || prevRow.level2 !== row.level2 || prevRow.level1 !== row.level1) {
      let rowspan = 1
      for (let i = rowIndex + 1; i < QzData.value.length; i++) {
        if (QzData.value[i].level2 === row.level2 && QzData.value[i].level1 === row.level1) {
          rowspan++
        } else {
          break
        }
      }
      return { rowspan, colspan: 1 }
    }
    return { rowspan: 0, colspan: 0 }
  }

  // 三级指标和权重不合并(第4列和第5列)
  return { rowspan: 1, colspan: 1 }
}

// 更新权重的方法 相同指标权重值同步更新
const updateWeight = (value, row, field) => {
    let data = [...QzData.value]
    console.log('更新权重方法', value, row, field)
    // 更新一级指标权重
    if (field === 'sourceStatus') {
        // 找到所有相同level1的行
        const level1 = row.level1
        data.forEach(item => {
            if (item.level1 === level1) {
                item.sourceStatus = value
            }
        })
    }
    // 更新二级指标权重
    else if (field === 'sourceLevel') {
        // 找到所有相同level1和level2的行
        const level1 = row.level1
        const level2 = row.level2
        data.forEach(item => {
            if (item.level1 === level1 && item.level2 === level2) {
                item.sourceLevel = value
            }
        })
        // 重新计算一级指标(sourceStatus)
        const level1Sums = data.reduce((acc, item) => {
            // 对每个一级指标下的所有二级指标sourceLevel求和
            if (!acc[item.level1]) {
                acc[item.level1] = 0;
            }
            // 确保每个二级指标只加一次（去重）
            if (item.level3) { // 如果是三级指标行
                const key = `${item.level1}-${item.level2}`;
                if (!acc.seenKeys) acc.seenKeys = new Set();
                if (!acc.seenKeys.has(key)) {
                    acc[item.level1] += item.sourceLevel;
                    acc.seenKeys.add(key);
                }
            }
            return acc;
        }, {});

        // 3. 更新sourceStatus
        data = data.map(item => ({
            ...item,
            sourceStatus: level1Sums[item.level1] || 0
        }));
    }
    // 更新三级指标权重
    else if (field === 'admissionScore') {
        data = calculateAllWeights(data);
    }

    QzData.value = data
    console.log('更新后的权重值：', QzData.value)

}

const formDrawerRef = ref(null)
const quanzhong = () => {
  formDrawerRef.value.open();
    fetchWeightsAndUpdate({
        selectlabel,
        QzData,
        calculateAllWeights,
    });

}

// 动态控制权重的方法  子权重总和不能超过父权重
const syztWeights = ref(QzData.value[0].sourceStatus != null ? QzData.value[0].sourceStatus : 0);
const pygcWeights = ref(QzData.value[6].sourceStatus != null ? QzData.value[6].sourceStatus : 0);
const xsfzWeights = ref(QzData.value[12].sourceStatus != null ? QzData.value[12].sourceStatus : 0);
const largestWeight = 100
const handleWeightChange = (row, level, value) => {
  if (level === 1) {
    console.log('一级指标权重变化：', row.level1, value);
    console.log('当前权重值：', QzData.value);

    // 更新对应指标的权重值
    if (row.level1 === '生源状态') {
      syztWeights.value = value;
    } else if (row.level1 === '培养过程') {
      pygcWeights.value = value;
    } else if (row.level1 === '学生发展与就业') {
      xsfzWeights.value = value;
    }

    // 计算当前三个指标的总和
    const total = syztWeights.value + pygcWeights.value + xsfzWeights.value;

    // 如果总和超过最大值，调整当前修改的值
    if (total > largestWeight) {
      // 找出不是当前修改的另外两个指标
      const otherWeights =
        row.level1 === '生源状态' ? pygcWeights.value + xsfzWeights.value :
          row.level1 === '培养过程' ? syztWeights.value + xsfzWeights.value :
            syztWeights.value + pygcWeights.value;

      // 计算允许的最大值
      const maxAllowed = largestWeight - otherWeights;

      // 限制当前值不超过允许的最大值
      if (value > maxAllowed) {
        value = maxAllowed;

        // 更新对应的ref值
        if (row.level1 === '生源状态') {
          syztWeights.value = maxAllowed;
          row.sourceStatus = maxAllowed;
        } else if (row.level1 === '培养过程') {
          pygcWeights.value = maxAllowed;
          row.sourceStatus = maxAllowed;
        } else if (row.level1 === '学生发展与就业') {
          xsfzWeights.value = maxAllowed;
          row.sourceStatus = maxAllowed;
        }
      }
    }
  } else if (level === 2) {
    console.log('二级指标权重变化：', row.level2, value);
    console.log('当前权重值：', QzData.value);

    // 获取所属一级指标的权重
    let parentWeight = 0;
    let parentField = '';

    if (row.level2 === '专业认可度' || row.level2 === '生源水平') {
      parentWeight = QzData.value[0].sourceStatus;
      parentField = 'sourceStatus';
    } else if (row.level2 === '高层次人才' || row.level2 === '师资队伍' ||
      row.level2 === '资源配置' || row.level2 === '课程质量') {
      parentWeight = QzData.value[6].sourceStatus;
      parentField = 'sourceStatus';
    } else if (row.level2 === '学生成长' || row.level2 === '就业质量') {
      parentWeight = QzData.value[12].sourceStatus;
      parentField = 'sourceStatus';
    }
    console.log('parentWeight', parentWeight);

    // 计算当前二级指标组的总和
    // 根据 level1 动态分组 + 去重，避免硬编码
    const currentGroup = QzData.value.reduce((acc, item) => {
      if (item.level1 === row.level1 && !acc.some(i => i.level2 === item.level2)) {
        acc.push(item);
      }
      return acc;
    }, []);
    const currentGroupSum = currentGroup.reduce((sum, item) => sum + (item.sourceLevel || 0), 0);

    console.log('currentGroupSum', currentGroupSum)
    console.log('currentGroup', currentGroup)
    // 校验并修正
    const newSum = currentGroupSum + (value - (row.sourceLevel || 0));
    if (newSum > parentWeight) {
      const maxAllowed = parentWeight - (currentGroupSum - (row.sourceLevel || 0));
      value = Math.max(0, maxAllowed); // 确保不小于 0
      row.sourceLevel = value;
    }
  }else if(level ===3){
    console.log('二级指标权重变化：', row.level3, value);
    console.log('当前权重值：', QzData.value);
    let parentWeight = 0;
    // 根据 level1 动态分组 + 去重，避免硬编码
    const currentGroup = QzData.value.reduce((acc, item) => {
      if (item.level2 === row.level2 && !acc.some(i => i.level3 === item.level3)) {
        acc.push(item);
      }
      return acc;
    }, []);
    const currentGroupSum = currentGroup.reduce((sum, item) => sum + (item.admissionScore || 0), 0);

    console.log('currentGroupSum', currentGroupSum)
    console.log('currentGroup', currentGroup)
    parentWeight = currentGroup[0].sourceLevel

    const newSum = currentGroupSum + (value - (row.admissionScore || 0));
    if (newSum > parentWeight) {
      const maxAllowed = parentWeight - (currentGroupSum - (row.admissionScore || 0));
      value = Math.max(0, maxAllowed); // 确保不小于 0
      row.admissionScore = value;
    }
  }
}

// //将三级指标提取成数组
// const admissionScores = QzData.value.map(item => item.admissionScore !== null ? item.admissionScore : 0);

const onSubmit = () => {
  QzData.value.forEach(item => {
    if(item.admissionScore == null || item.sourceLevel == null || item.sourceStatus == null){
      ElMessage.error('请填写所有指标权重')
      return
    }
  })
  updateTableData();
  const qzstore = useQzStore();
  qzstore.updateQzdata(tableData.value);
  // console.log('admissionScores', admissionScores)
  axios.post('http://localhost:8081/setweight',
    [{
        "qzlx": selectlabel2.value,
        "zbh": "1",
        "zbqz": QzData.value[0].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "2",
        "zbqz": QzData.value[1].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "3",
        "zbqz": QzData.value[2].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh":"4",
        "zbqz": QzData.value[4].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "5",
        "zbqz":  QzData.value[5].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "6",
        "zbqz": QzData.value[6].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "7",
        "zbqz": QzData.value[7].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "8",
        "zbqz": QzData.value[8].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "9",
        "zbqz": QzData.value[9].admissionScore
    },{
        "qzlx":  selectlabel2.value,
        "zbh": "10",
        "zbqz": QzData.value[10].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "11",
        "zbqz": QzData.value[11].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "12",
        "zbqz": QzData.value[13].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "13",
        "zbqz": QzData.value[14].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "14",
        "zbqz": QzData.value[15].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "15",
        "zbqz": QzData.value[16].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "16",
        "zbqz": QzData.value[17].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "17",
        "zbqz": QzData.value[18].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "18",
        "zbqz": QzData.value[19].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "19",
        "zbqz": QzData.value[20].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "20",
        "zbqz": QzData.value[21].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "21",
        "zbqz": QzData.value[22].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "22",
        "zbqz": QzData.value[23].admissionScore
    },{
        "qzlx":  selectlabel2.value,
        "zbh":"23",
        "zbqz": QzData.value[24].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "24",
        "zbqz": QzData.value[25].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh":"25",
        "zbqz": QzData.value[3].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "26",
        "zbqz": QzData.value[12].admissionScore
    },{
        "qzlx": selectlabel2.value,
        "zbh": "27",
        "zbqz": QzData.value[0].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "28",
        "zbqz": QzData.value[5].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "29",
        "zbqz": QzData.value[7].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "30",
        "zbqz": QzData.value[10].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "31",
        "zbqz": QzData.value[13].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "32",
        "zbqz": QzData.value[15].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "33",
        "zbqz": QzData.value[18].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "34",
        "zbqz": QzData.value[22].sourceLevel
    },{
        "qzlx": selectlabel2.value,
        "zbh": "35",
        "zbqz": QzData.value[0].sourceStatus
    },{
        "qzlx": selectlabel2.value,
        "zbh": "36",
        "zbqz": QzData.value[7].sourceStatus
    }, {
        "qzlx": selectlabel2.value,
        "zbh": "37",
        "zbqz": QzData.value[18].sourceStatus
    }],
      {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer ' + localStorage.getItem('jwt_token')
          }
      }
  ).then(res => {
    console.log(res)
    ElMessage.success('保存成功')
  }).catch(err => {
    console.log(err)
    ElMessage.error('保存失败')
  })
  formDrawerRef.value.close();
}
</script>

<style scoped>
  .span1{
    font-size: 20px;
    font-weight: bold;
    color: #808080;
    margin: 10px 5px;
  }
  .button{
    margin-top: 60px;
  }
</style>
